package com.enfi.api.modules.db.service.impl;

import com.enfi.api.modules.db.base.BaseQuery;
import com.enfi.api.modules.db.base.BaseServiceImpl;
import com.enfi.api.modules.db.dao.WarningSuggestionRepository;
import com.enfi.api.modules.db.entity.WarningSuggestion;
import com.enfi.api.modules.db.entity.WarningView;
import com.enfi.api.modules.db.service.WarningService;
import com.enfi.api.modules.db.service.WarningSuggestionService;
import com.enfi.api.util.SecUser;
import com.enfi.api.util.SpeUtils;
import com.enfi.api.util.UserUtils;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 预警內容建议(WarningSuggestion)表服务实现类
 *
 * @author wind
 * @since 2020-04-07 15:59:43
 */
@Service("warningSuggestionService")
@NoRepositoryBean
public class WarningSuggestionServiceImpl extends BaseServiceImpl<WarningSuggestionRepository,WarningSuggestion,Integer> implements WarningSuggestionService {
    @Autowired
    private WarningService warningService;
    @Override
    protected Object query(BaseQuery baseQuery, WarningSuggestion warningSuggestion, Pageable pageable) {
        Assert.isTrue(baseQuery.getQuery()!=null&&baseQuery.getQuery().getQueryType()!=null,"查询方式不为空");
        switch (baseQuery.getQuery().getQueryType()){
            case "":
                SecUser secUser= UserUtils.getSecUser();
                Page<WarningSuggestion> page= this.baseRepository.findAll((root, query, builder)->{
                    List<Predicate> predicates= SpeUtils.getInstance().toSpec(warningSuggestion,baseQuery,root,builder);
                    root.fetch("feedbacks", JoinType.LEFT);
                    query.where(predicates.stream().toArray(Predicate[]::new));
                    return null;
                },pageable);
                return page;
            default:
                return super.query(baseQuery,warningSuggestion,pageable);
        }
    }

    @Override
    public boolean insert(WarningSuggestion warningSuggestion) {
        boolean flag=super.insert(warningSuggestion);
        if(flag){
            warningService.findById(warningSuggestion.getWarningId()).ifPresent(v->{
                v.setStatus(3);
                warningService.save(v);
            });
        }
        return flag;
    }
}